<?
class ccdsFileManager
	extends ccdsBackendPlugin
{
	public $name = "ccdsFileManager";
	private $aExpand = array();
	private $percent = 1;
	private $inc = 1;
	private $objResponse;

	function __construct()
	{
		parent::__construct();

		$this->xajax = ccdsXajax::getInstance();


		$this->objResponse = new ccdsResponse();
		
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerOpen", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerFileListing", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerListView", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerFileDetails", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerFileSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerFileSaveDetails", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerDirSelectorOpen", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerDirSelectorOpenDir", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerCreateFolder", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerUpload", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerReturnImage", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerReturnGallery", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerReturnFile", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerReturnFiles", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerSearch", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerDelete", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerRotate", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerCrop", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "FileManagerSaveFile", $this->name );


	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */


	function FileManagerUpload ( $aFormValues) 
	{
		
		

		$root_dir = $this->getRootDir( $aFormValues );
		
		if (isset($_FILES['filemanager_upload_file']['tmp_name'])) {
			$src = $_FILES['filemanager_upload_file']['tmp_name'];
			$name = $this->tools->getRewriteFilename($_FILES['filemanager_upload_file']['name']);
			$dest = $root_dir.$aFormValues['dir'].'/'.$name;
			move_uploaded_file($src,$dest);
			if (is_file($dest)) chmod($dest,$this->config->get('FILE_CHMOD'));
			$this->objResponse->loadcommands($this->FileManagerListView($aFormValues));
		}		

		return $this->objResponse;
	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function FileManagerDirSelectorOpenDir( $aFormValues ) 
	{


		$root_dir = $this->getRootDir($aFormValues);

		$query = "SELECT * FROM projects WHERE project_id='".addslashes($aFormValues['project_id'])."' LIMIT 1";
		$res = $this->ccdSQL->query($query);
		$row = $this->ccdSQL->fetch_assoc($res);
		if ($row['project_dir'] != '') {

			$aFormValues['root_dir'] .= '/'.$row['project_dir'];
			$dir = $row['project_dir'];
			
			$aFormValues['dir'] = $aFormValues['dir'];
			$name = $dir;
		}  else {
			$dir = $aFormValues['dir'];
			$name = $aFormValues['root'];
		}

		
		$aFormValues['FieldType'] = "*dir*"; 
		$dirs = $this->getPreparedDirArray($aFormValues);
		$this->objResponse->script($this->tools->strip("
		$('#CMS_dir_selector').xTree('add',".json_encode(
			array(
				"parent" => $aFormValues['parent_id'],
				"elements" => $dirs
			)
		).");	"));
		$this->objResponse->script("$('#CMS_dir_selector').xTree('open',{id:'".$aFormValues['parent_id']."'})");

		return $this->objResponse;
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function FileManagerDirSelectorOpen( $aFormValues ) 
	{
		
		$root_dir = $this->getRootDir($aFormValues);

		$query = "SELECT * FROM projects WHERE project_id='".addslashes($aFormValues['project_id'])."' LIMIT 1";
		$res = $this->ccdSQL->query($query);
		$row = $this->ccdSQL->fetch_assoc($res);
		if ($row['project_dir'] != '') {

			$aFormValues['root_dir'] .= '/'.$row['project_dir'];
			$dir = $row['project_dir'];
			
			$aFormValues['dir'] = $aFormValues['dir'];
			$name = $dir;
		}  else {
			$dir = $aFormValues['dir'];
			$name = $aFormValues['root'];
		}
		
		$aFormValues['FieldType'] = "*dir*"; 
		$dirs = $this->getPreparedDirArray($aFormValues, $dir.'/');
		$new_dirs = array();
		foreach ($dirs as $key => $value) $new_dirs[] = $value;
		unset($dirs);
		$elements = array(
			"icon" => $this->config->get("LIBRARY_WEB")."/famfamfam/icons/package.png",
			"id" => "dir_selector_".$row['project_id'],
			"name" => $name,
			"onOpen" => "function(parent_id) {xajax.request({ccdsfun:'FileManagerDirSelectorOpenDir',ccdsclass:'ccdsFileManager'},{parameters:[{parent_id:parent_id}]});}",
			"onSelect" => "",
			"folder" => true,
			"elements" => $new_dirs
		);
		
		$this->objResponse->script("
try {
$('<div id=\"CMS_dir_selector\"/>').
		xWindow({
			title: 'Verzeichnisauswahl',
			dialog: true,
			statusBar: false,
			height: 320,
			width:300,
			buttons: {
				ok: {
					title: 'Ok',
					onclick: function(){
						var foo=this;
						$('#CMS_dir_selector').xTree('select', function(xTree, elems){
							if (!elems[0]) {
									alert('Bitte w&auml;hlen sie ein Verzeichnis.');
							} else {
								xajax.$('".$aFormValues['field']."').value = CMS.DirSelector.selected;
								xajax.$('".$aFormValues['field']."_label').innerHTML=CMS.DirSelector.selected;
								foo.destroy();
								foo = null;
							}						
						});


					}
			},
				abort: {
					title: 'Abort',
					onclick: function(){
						this.destroy();
					}
				}
			}
		});

} catch (ex) {
	alert(ex);
}
		");

		$this->objResponse->script("
		
		$('#CMS_dir_selector').xTree(".json_encode(
			array(
				"animate" => false,
				"onSelect" => "alert(id)",
				"elements" => array($elements) 
			
			)
		).")
		
		");
		
		
		return $this->objResponse;
	}



	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	private function getRootDir( &$aFormValues) {

		if (true === $aFormValues['root_set']) return $aFormValues['root_dir'];

		switch ( $aFormValues['root'] )
		{
			case "media":
				$root_dir = $this->config->get( 'MEDIA_DIR' );
				break;

			case "extensions":
				$root_dir = $this->config->get( 'EXTENSION_DIR' );
				break;

			default : $root_dir = $this->config->get('MEDIA_DIR');
			break;
		}

		if ( $aFormValues['FieldType'] == "" )
			$aFormValues['FieldType'] = "ALL";
		$root_dir .="/";
		
		//if ('/' != substr($aFormValues['dir'],-1)) $aFormValues['dir'].="/";
		
		$aFormValues['root_set'] = true;
		$aFormValues['root_dir'] = $root_dir;
		return $root_dir;
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	private function getListing( $aFormValues) 
	{
		$root_dir = $this->getRootDir( $aFormValues ) ;
		$files = $this->tools->getFileListing( $root_dir, $aFormValues['dir'], $aFormValues['FieldType'] );		
		return array($root_dir,$files);
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */




	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	private function prepareFile ( $file, $dir,$root,$root_dir, $index = false, $max = false) {

			$iCache = ccdsImageCache::getInstance();
			if ($index) {
				
				$file_id = crc32($root_dir.$file['dir'].$file['name']);
				$query = "SELECT * FROM file_index WHERE file_crc='".$file_id."'";
				$res = $this->ccdSQL->query($query);
				if (!$file_row = $this->ccdSQL->fetch_assoc($res)) 
				{
					$query = "INSERT IGNORE INTO file_index 
										( 
											file_crc,
											file_root,
											file_dir,
											file_name
										)
										VALUES(
											'".$file_id."',
											'".addslashes($root)."',
											'".$this->ccdSQL->real_escape_string($file['path'])."',
											'".$this->ccdSQL->real_escape_string($file['name'])."'
										)
										";
					$this->ccdSQL->query($query);
					$file_row = array();
				} else {
					$file['keywords'] = $file_row['file_keywords'];
					$file['descr'] = $file_row['file_descr'];
				}
			}
			if ("folder" == $file['type']) {
			} elseif ( "image" == $file['type']) {
				$file_path = $root_dir.$dir.'/'.$file['name'];
				if ($max) {
					$img_src = $iCache->img_cache_resize($file_path,374,256,0,80);
				} else {
					$img_src = $iCache->img_cache_resize($file_path,78,78,0,80);
				}
				$file['preview'] = $img_src['src'];
			}		
		return $file;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	private function ExpandIdAdd($id) {
		
		$this->aExpand[] = $id;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	private function ExpandIdsGet() {
		return 0 < count($this->aExpand) ? $this->aExpand : false;
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	private function getPreparedFileArray($aFormValues,$path='') 
	{

		$path = str_replace('//','/',$path);

		list($root_dir,$files) = $this->getListing($aFormValues);
		
		if (false != $this->objResponse) 
		{
			$count = count($files);
			$this->percent = 0;
			$this->inc = 0 == $count ? 0 : round(80/$count);
			
		}
		
		$index = "media" == $aFormValues['root'] ? true : false;
		$i=0;
		foreach ($files as $key => $file) {
			if ('/' != substr($file['path'],0,1)) {
				$files[$key]['path'] = '/'.$file['path'];
				$file['path']='/'.$file['path'];
			}
			++$i;
			$files[$key] = $this->prepareFile($file,$aFormValues['dir'],$aFormValues['root'],$root_dir,$index);
			if (false != $this->objResponse) 
			{
				$this->percent +=$this->inc;
				
				if ($i%4) {
					$this->objResponse->updateProgress($this->percent);
					$this->objResponse->flush();				
				}
			}		

			if ( ("folder" == $file['type']) && ('' != $aFormValues['open_dir']) && (false !== strpos($aFormValues['open_dir'],$path.$file['name'].'/')) )
			{

				$files[$key]['elements']=array();
				$files[$key]['elements'] = $this->getPreparedFileArray(array(
					'root' => $aFormValues['root'],
					'dir' => $path.$file['name'],
					'project_id' => $aFormValues['project_id'],
					'open_dir' => $aFormValues['open_dir']
				),$path.$file['name']."/");
			}
		}		
		return $files;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */


	private function getPreparedDirArray($aFormValues) 
	{

		list($root_dir,$dirs) = $this->getListing($aFormValues);
		foreach ($dirs as $key => $dir) {
			if ('folder' == $dir['type']) {
				$dirs[$key]['folder'] = true;
				$dirs[$key]['icon'] = '/ccds_library/famfamfam/icons/folder.png';
				$dirs[$key]['onNameClick'] = "
					function (id) {
						
						CMS.DirSelector.selected='".$dir['path'].$dir['name']."';
					}				
				";
				$dirs[$key]['onOpen'] = $this->tools->strip("function(id){	
					xajax.request(
						{ccdsfun:'FileManagerDirSelectorOpenDir',ccdsclass:'ccdsFileManager'}
						,
						{
							parameters:[{
								dir:'".$aFormValues['dir'].$dir['name']."/',
								root:'".$aFormValues['root']."',
								parent_id:id,
								project_id:'".$aFormValues['project_id']."'
							}]
						}
					);	
				};");
			}
		}		
		return $dirs;
	}
	
	// -------------------------------------------------------------------------------------------------------------------

	private function return_bytes($val) {
	    $val = trim($val);
	    $last = strtolower($val[strlen($val)-1]);
	    switch($last) {
	        case 'g':
	            $val *= 1024;
	        case 'm':
	            $val *= 1024;
	        case 'k':
	            $val *= 1024;
	    }
	
	    return $val;
	}

	// -------------------------------------------------------------------------------------------------------------------
	
	private function return_upload_limit() {
		
		$post_max = ini_get('post_max_size');
		$post_max_bytes = $this->return_bytes($post_max);
		
		$upload_max = ini_get('upload_max_filesize');
		$upload_max_bytes = $this->return_bytes($upload_max);
		
		return $post_max_bytes < $upload_max_bytes ? $post_max_bytes : $upload_max_bytes;		
	}

	// -------------------------------------------------------------------------------------------------------------------
	
	function FileManagerOpen( $aFormValues )
	{ 

		$this->objResponse->openProgress();

		$root_dir = $this->getRootDir($aFormValues);
		$current_path = '/';
		if ( ( "" == $aFormValues['open_dir'] && $_COOKIE['FM_PATH'] != '') ) 
		{
			$aFormValues['open_dir']=$_COOKIE['FM_PATH'].'/';
		}
		if ('/' == $aFormValues['open_dir']) $aFormValues['open_dir'] = '';
//		
		if ($this->config->get('FM_SEP_DIRS')) {
			$query = "SELECT * FROM projects WHERE project_id='".addslashes($aFormValues['project_id'])."' LIMIT 1";
			$res = $this->ccdSQL->query($query);
			$row = $this->ccdSQL->fetch_assoc($res);
	
	
			if ($row['project_dir'] != '') {
				$dir = $row['project_dir'];
				$aFormValues['dir'] = $row['project_dir'].$aFormValues['dir'];
				if ('' != $aFormValues['open_dir'])
					$aFormValues['open_dir'] = $aFormValues['open_dir'];
			}  else {
				$dir = $aFormValues['dir'];
			}
		} else {
				$dir = $aFormValues['dir'];
		}

		if ('/' != substr($dir,0,1)) {
			$dir = '/'.$dir;
		}

		
		$root_id = crc32($root_dir.$dir);
		$elements = $this->getPreparedFileArray( $aFormValues, $dir.'/' );

		$files = array( array
		(

			"id" => $root_id,
			"type" => "folder",
			"name" => $dir, //'',
			"path" => $dir,
			"elements" =>  $elements
		));
		$this->objResponse->updateProgress($this->percent);
		$this->objResponse->flush();
 
 		$current_path = !empty($aFormValues['open_dir']) ? $aFormValues['open_dir'] : $aFormValues['dir'];

		$aFormValues['multiple'] = true == $aFormValues['multiple'] ? 'true' : 'false';

		if ('/' != $current_path &&  '/' == substr($current_path,-1)) {
			$current_path = substr($current_path,0,strlen($current_path)-1);
		}
		$current_path = str_replace('//','/',$current_path);
		

		$this->objResponse->script("
		$('<div id=\"filemanager\"/>').
		filemanager({
			iconsRoot : '/ccds_library/famfamfam/icons/',
			root:'/media/',
			icons : ".json_encode($this->tools->file_icons).",
			elements: ".json_encode($files).",
			height: 400,
			width:850,
			previewPath:'',
			labels:CMS.lang.FM,
			multiselect:".$aFormValues['multiple'].",
			currentPath:'".$current_path."',
			sort:['name','asc'],
			xWindowOptions: {
				modal: true,
				title:'Dateimanager',
				buttons: {
					save: {
						title: 'Auswaehlen',
						focus: true,
						modal: false,
						onclick: function(){
 							$('#filemanager').filemanager('select',function(files) {
 							CMS.FileManager.returnfiles(files);
 							});
							this.destroy();
						}
					}
				}
			},
			cut : function() {
				console.log(arguments);
			},
			copy : function () {
				console.log(arguments);
			},
			uploadOpen: function() {
				 xajax.ext.SWFupload.tools.transField('filemanager_upload_file',{
						file_types : '*.*', 
						file_types_description: 'alle Dateien',
						file_size_limit : '".$this->return_upload_limit()." B',
						post_params: {PHPSESSID : '".session_id()."'},
						button_image_url : 'img/button_500x22.gif',
						button_width : 270,
						button_height : 22,
						button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
						button_image_url : 'img/button_500x22.gif'
						},
					true
				 	);
				 xajax.$('filemanager_upload_form').onsubmit=function() {
			
					$('#filemanager').filemanager('path',
						function(path) { 
											xajax.request(
												{ccdsclass:'ccdsFileManager',ccdsfun:'FileManagerUpload'},
												{
													parameters:[
													{
														dir:path,
														root:'".$aFormValues['root']."',
														project_id:'".$aFormValues['project_id']."'
													}
													],
													mode:'SWFupload',SWFfield:'filemanager_upload_file'
												}
											);
						}
					);
				 	return false;	
				 
				 }
			},
			uploadClose: function() 
			{
				xajax.ext.SWFupload.tools.destroyField('filemanager_upload_file');		
			},
			ls: function (path) 
			{
				var dirs = path.split('/');
				dirs.pop();
				path = dirs.join('/');
				xajax.request(
					{ccdsfun:'FileManagerListView',ccdsclass:'ccdsFileManager',ccdscomet:1}
					,
					{
						context:this,
						comet:1,
						parameters:[{
							dir : path,
							root : '".$aFormValues['root']."',
							project_id : '".$aFormValues['project_id']."'
						}]
					}
				);
			},
			open: function( id, path, name, type,view ) 
			{
					if ('folder' == type) {
						xajax.request(
							{ccdsfun:'FileManagerListView',ccdsclass:'ccdsFileManager',ccdscomet:1}
							,
							{
								context:this,
								comet:1,
								parameters:[{
									dir : path+name ,
									root : '".$aFormValues['root']."',
									parent_id : id,
									project_id : '".$aFormValues['project_id']."'
								}]
							}
						);
					} else {
						xajax.request(
							{ccdsfun:'FileManagerFileDetails',ccdsclass:'ccdsFileManager'}
							,
							{
								context:this,
								parameters:[{
									dir : path ,
									filename: name,
									root : '".$aFormValues['root']."',
									parent_id : id,
									project_id : '".$aFormValues['project_id']."'
								}]
							}
						);
					}
			},
			expand:function(id,path,name) {
 
					xajax.request(
						{ccdsfun:'FileManagerFileListing',ccdsclass:'ccdsFileManager',ccdscomet:1}
						,
						{
							comet:1,
							context:this,
							parameters:[{
								dir : path+name,
								root : '".$aFormValues['root']."',
								parent_id : id,
								project_id : '".$aFormValues['project_id']."'
							}]
						}
					);	
			},
			createFolder: function(dir,name,cb) {
					//console.log(arguments);
					xajax.request(
						{ccdsfun:'FileManagerCreateFolder',ccdsclass:'ccdsFileManager',ccdscomet:1},
						{
							comet:1,
							context:this,
							parameters:[{
								dir : dir,
								root : '".$aFormValues['root']."',
								new_dir : name,
								project_id : '".$aFormValues['project_id']."'
							}]
						}
					);	
			},
			saveDetails: function(file,params) {
					xajax.request(
						{ccdsfun:'FileManagerFileSaveDetails',ccdsclass:'ccdsFileManager'}
						,
						{
							context:this,
							parameters:[{
								dir : file.dir,
								name: file.name,
								id:file.id,
								root : '".$aFormValues['root']."',
								project_id : '".$aFormValues['project_id']."',
								values:params
							}]
						}
					);
			},
			search: function(sq,path) {
					xajax.request(
						{ccdsfun:'FileManagerSearch',ccdsclass:'ccdsFileManager'}
						,
						{
							context:this,
							parameters:[{
								dir : path,
								sq : sq,
								root : '".$aFormValues['root']."',
								project_id : '".$aFormValues['project_id']."'
							}]
						}
					);

			},
			remove: function(id,path,name,type) {
				xajax.request(
					{ccdsfun:'FileManagerDelete',ccdsclass:'ccdsFileManager'}
					,
					{
						context:this,
						parameters:[{
							dir : path,
							name : name,
							root : '".$aFormValues['root']."',
							project_id : '".$aFormValues['project_id']."'
						}]
					}
				);
			
			},
			edit : function(id,path,name,type) 
			{
				if ('image' == type) 
				{

					$('<div />').imageEditor(
					{

						xWindowOptions:{title: 'bla'},
						root:'/media/',
						path:path,
						fileName:name,
						aspectRatio:3/4,
						rotate:function(file,direction) {
							xajax.request(
								{ccdsfun:'FileManagerRotate',ccdsclass:'ccdsFileManager'},
								{
									parameters:[{
										root : '".$aFormValues['root']."',
										project_id : '".$aFormValues['project_id']."',
										name:file,
										direction:direction
									}],
									context:this
								}
							);
						},
						crop:function(file,crop) {
							xajax.request(
								{ccdsfun:'FileManagerCrop',ccdsclass:'ccdsFileManager'},
								{
									parameters:[{
										root : '".$aFormValues['root']."',
										project_id : '".$aFormValues['project_id']."',
										name:file,
										crop:crop
									}],
									context:this
								}
							);
						},
						save:function(tmpfile,path) {
							foo = this;
							$('<div/>').xWindow(
										'prompt', 
										{
											title: 'Namen Eingabe',
											content:'Bitte geben Sie ihren Namen an:'
										},
										function(val, elem){
											if ('' == val) {
												elem.trigger('error','Bitte geben Sie einen Namen fuer die Datei ein!');
												return false;
											}
											xajax.request(
												{ccdsfun:'FileManagerSaveFile',
												ccdsclass:'ccdsFileManager'},
												{
													parameters:[{
														temp : tmpfile,
														dir : path,
														newname : val,
														root : '".$aFormValues['root']."',
														project_id : '".$aFormValues['project_id']."'
													}],
													context: {
														elem:\$elem,
														window:this,
														imageEditor:foo
													}
												}
											);

										}
									);
						}
					});

				
				}
			}
		});

		");

 
		$this->objResponse->updateProgress($this->percent);
		$this->objResponse->flush();

		if ( !is_dir( $root_dir.$aFormValues['dir'] ) )
			$aFormValues['dir'] = "";
 
		$this->objResponse->updateProgress(100);
		$this->objResponse->flush();
		$this->objResponse->closeProgress();

		return $this->objResponse;
	}
	// -------------------------------------------------------------------------------------------------------------------





	function FileManagerSaveFile ($aFormValues) {

		
		
		$root_dir = $this->getRootDir($aFormValues);
		$file = $root_dir.$aFormValues['dir'].$aFormValues['newname'];
		
		$regex = "/[^a-zA-Z0-9\.-_]/";
		
		if (is_file($file)) {
			$this->objResponse->script("this.elem.trigger('error','Der Dateiname ist bereits vergeben!')");
		} elseif(1 == preg_match($regex,$aFormValues['newname'])) {
			$this->objResponse->script("this.elem.trigger('error','Der Dateiname darf keine Umlaute oder Leerzeichen enthalten!')");
		}else {
			$src = $this->config->get('DOC_ROOT').$this->config->get('WEB_ROOT').$aFormValues['temp'];
			copy($src,$file);
			chmod($file,$this->config->get('FILE_CHMOD'));
			$this->objResponse->script("this.window.destroy()");
			$this->objResponse->script("this.imageEditor.destroy()");
			
		}				
		
		return $this->objResponse;		
	}

	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerRotate ($aFormValues) {

		


		$iCache = ccdsImageCache::getInstance();
		$file = $this->config->get('DOC_ROOT').$this->config->get('WEB_ROOT').$aFormValues['name'];
		
		$direction = $aFormValues['direction'] == 'left' ? -90 : 90;
		
		$img = $iCache->rotate($file,$direction);

		$this->objResponse->script("this.update('/".$img."');");

		return $this->objResponse;		
	}
	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerCrop ($aFormValues) {

		


		$iCache = ccdsImageCache::getInstance();
		
		$file = $this->config->get('DOC_ROOT').$this->config->get('WEB_ROOT').$aFormValues['name'];
		$crop = $aFormValues['crop'];

		$img = $iCache->crop($file,$crop['width'],$crop['height'],$crop['left'],$crop['top']);
		$this->objResponse->script("this.update('/".$img."');");

		return $this->objResponse;		
	}


	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerDelete ($aFormValues) {

		
	
		

		$this->objResponse->openProgress();
		$this->objResponse->flush();

		$root_dir = $this->getRootDir($aFormValues);
		$dest = $root_dir.$aFormValues['dir'].$aFormValues['name'];
		if (is_dir ($dest)) {
			$files = $this->tools->getFileListing( $root_dir, $aFormValues['dir'], $aFormValues['FieldType'] );		
			if (0 < count(files)) {
				$this->objResponse->call('CMS.AlertWindow','Das Verzeichnis enth&auml;lt noch weitere Dateien oder Verzeichnisse!');
			} else {
				@rmdir($dest);
			}
		} else {
			@unlink($dest);
		}

		$this->objResponse->loadcommands($this->FileManagerListView($aFormValues));
		
		return $this->objResponse;		
		
		
	}

	function FileManagerFileListing( $aFormValues )
	{

	

		$this->objResponse->openProgress();
		$this->objResponse->flush();

		$files = $this->getPreparedFileArray( $aFormValues );

		$this->objResponse->script("
			
			this.path('".$aFormValues['dir']."');
			this.updateTreeItem({parent:'".$aFormValues['parent_id']."',elements:".json_encode($files)."});
			this.expand(['".$aFormValues['parent_id']."']);
		");

		$this->objResponse->closeProgress();
		
		return $this->objResponse;
	}

	// -------------------------------------------------------------------------------------------------------------------
	function FileManagerCreateFolder( $aFormValues )
	{

		

		$root_dir = $this->getRootDir($aFormValues);

		$dir = str_replace("/","",$aFormValues['dir']);
		$aFormValues['parent_id'] = crc32($root_dir.$dir);
		$name = $this->tools->getRewriteFilename($aFormValues['new_dir']);
		$new_dir = $root_dir.'/'.$aFormValues['dir'].'/'.$name;
		if (is_dir($new_dir)) {
			$this->objResponse->call("CMS.AlertWindow","Es existiert bereits ein Verzeichnis mit dem Namen!");
			return $this->objResponse;
		} else {
			
			$this->tools->mkdir($new_dir);
			$this->objResponse->loadcommands($this->FileManagerListView($aFormValues));

			$this->objResponse->loadcommands($this->FileManagerFileListing($aFormValues));
			$this->objResponse->script("this.resetForms();");
			$this->objResponse->flush();
		}

		return $this->objResponse;
	}


	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerListView( $aFormValues )
	{
		$this->tools->set_cookie_fix_domain("FM_PATH", $aFormValues['dir'], time()+(180*3600*24),"/",$_SERVER['HTTP_HOST']);

		$files = $this->getPreparedFileArray( $aFormValues );
		$this->objResponse->script("
			$('#filemanager').filemanager('path','".$aFormValues['dir']."');
			$('#filemanager').filemanager('update',".json_encode($files).");
		");

		return $this->objResponse;
	}




	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerReturnFile( $aFormValues )
	{
		
		$file = $aFormValues['files'][0];
		if (!is_array($file)) return $this->objResponse;	
			
		$root_dir = $this->getRootDir($aFormValues);
		if ('media' == $aFormValues['root']) {
		
			$query = "SELECT * FROM file_index WHERE file_name='".addslashes($file['name'])."' AND file_dir='".addslashes($file['dir'])."'";
			$res = $this->ccdSQL->query($query);
			if ($row = $this->ccdSQL->fetch_assoc($res)) $this->objResponse->contextAssign('description.value',$row['file_descr']);
			
		}

    $file_src = $this->config->get('MEDIA_DIR').'/'.$file['path'].$file['name'];

    $file_size = filesize($file_src);
		$file_size = $this->tools->formatBytes($file_size);
		$end = $this->tools->get_file_extension($file_src);

		$size_str = $file_size;

		$this->objResponse->contextAssign('label.innerHTML',$file['name']);
		$this->objResponse->contextAssign('file.value',$file['name']);
		$this->objResponse->contextAssign('dir.value',(string) $file['path']);
		$this->objResponse->contextAssign('size.innerHTML',(string) $size_str);
		$this->objResponse->contextAssign('type.innerHTML',(string) $end);
		$this->objResponse->contextAssign('anchor.href',(string) "/media/".$file['path'].$file['name']);
		$this->objResponse->contextAssign('container.style.display','block');

			
		return $this->objResponse;
	}
	
	// -------------------------------------------------------------------------------------------------------------------
	

	function FileManagerReturnImage( $aFormValues )
	{

		

		$root_dir = $this->getRootDir($aFormValues);
		$file = $aFormValues['files'][0];
		if (!is_array($file)) return $this->objResponse;	
			
			$iCache = ccdsImageCache::getInstance();
	
			$img = $iCache->img_cache_return_array( array
			(
				"src" => "/media/".$file['path'].$file['name'],
				"width" => 125,
				"height" => 125
			));


      $img_src = $this->config->get('MEDIA_DIR').'/'.$file['path'].$file['name'];
      $size = $iCache->image_info($img_src);

      $file_size = filesize($img_src);
			$file_size = $this->tools->formatBytes($file_size);
			$end = $this->tools->get_file_extension($img_src);

			$size_str = $size['width'].'x'.$size['height'].', '.$file_size;
			
			$query = "SELECT * FROM file_index WHERE file_crc='".$aFormValues['files'][0]['id']."'";
			$res = $this->ccdSQL->query($query);
			if ($row = $this->ccdSQL->fetch_assoc($res)) $this->objResponse->contextAssign('description.value',$row['file_descr']);
			$this->objResponse->contextAssign('img.style.backgroundImage','url('.$img['src'].')');

			$this->objResponse->contextAssign('label.innerHTML',$file['name']);
			$this->objResponse->contextAssign('file.value',$file['name']);
			$this->objResponse->contextAssign('dir.value',(string) '/'.$file['path']);
			$this->objResponse->contextAssign('size.innerHTML',(string) $size_str);
			$this->objResponse->contextAssign('type.innerHTML',(string) $end);
			$this->objResponse->contextAssign('anchor.href',(string) "/media/".$file['path'].$file['name']);
			$this->objResponse->contextAssign('container.style.display','block');
		return $this->objResponse;
	}
	
	// -------------------------------------------------------------------------------------------------------------------
	
	
	function FileManagerReturnGallery( $aFormValues )
	{
		global $ccdSQL, $smarty;
		

		$query =
			"SELECT * FROM obj_index LEFT OUTER JOIN obj_names ON (obj_name_key_obj_id = obj_id AND obj_name_key_lang_id='".$_SESSION['CMS']['lang'][$aFormValues['project_id']]
			."')LEFT OUTER JOIN obj_versions_index ON obj_vers_key_obj_id = obj_id WHERE obj_id='"
			.$aFormValues['obj_id']."'";
		$res = $this->ccdSQL->query( $query );
		$obj = $this->ccdSQL->fetch_assoc( $res );
		$this->smarty->assign( "obj", $obj );
		$this->smarty->assign( "fieldname", $aFormValues['fieldname'] );

		$sHtml = '';
		$sScript = '';
		foreach ($aFormValues['files'] as $file) {
			$img = array
			(
				"picture_filename" => $file['name'],
				"picture_dir" => $file['path'],
				"picture_description" => ""
			);
	
	
				$query = "SELECT * FROM file_index WHERE file_crc='".$aFormValues['files'][0]['id']."'";
			$res = $this->ccdSQL->query($query);
			if ($row = $this->ccdSQL->fetch_assoc($res)) $img['picture_description'] = $row['file_descr'];
	
			$aFormValues['count']++;
	
			$id = crc32($file['dir'].$file['name']).rand( 0, 100 );
	
			$this->smarty->assign( "count", $id );
			$this->smarty->assign( "img", $img );
	
			$sHtml .= $this->smarty->fetch( $this->config->get( 'TPL_DIR' )."forms/gallery_append.tpl" );
			$sScript .= '$("#gallery_'.$aFormValues['fieldname'].'_'.$id.'_appear").slideDown("slow");';
		}
		$this->objResponse->contextAppend( "img_container.innerHTML", $sHtml );
		$this->objResponse->contextAssign( "container.style.display", 'block' );
		$this->objResponse->script( $sScript );

		$this->objResponse->call( 'Sortable.create', 'GallerySortable_'.$obj['obj_vers_id'].'_'.$aFormValues['fieldname'], array
		(
			"tag" => "div",
			"overlap" => 'horizontal',
			"constraint" => false
		));
		

		return $this->objResponse;
	}
	// -------------------------------------------------------------------------------------------------------------------
	
	
	function FileManagerReturnFiles( $aFormValues )
	{
		global $ccdSQL, $smarty;
		

		$query =
			"SELECT * FROM obj_index LEFT OUTER JOIN obj_names ON (obj_name_key_obj_id = obj_id AND obj_name_key_lang_id='".$_SESSION['CMS']['lang'][$aFormValues['project_id']]
			."')LEFT OUTER JOIN obj_versions_index ON obj_vers_key_obj_id = obj_id WHERE obj_id='"
			.$aFormValues['obj_id']."'";
		$res = $this->ccdSQL->query( $query );
		$obj = $this->ccdSQL->fetch_assoc( $res );
		$this->smarty->assign( "obj", $obj );
		$this->smarty->assign( "fieldname", $aFormValues['fieldname'] );

		$sHtml = '';
		$sScript = '';
		foreach ($aFormValues['files'] as $file) {
			$item = array
			(
				"file_name" => $file['name'],
				"file_dir" => $file['path'],
				"file_desc" => ""
			);
	
	
				$query = "SELECT * FROM file_index WHERE file_crc='".$aFormValues['files'][0]['id']."'";
			$res = $this->ccdSQL->query($query);
			if ($row = $this->ccdSQL->fetch_assoc($res)) $img['picture_description'] = $row['file_descr'];
	
			$aFormValues['count']++;
	
			$id = crc32($file['dir'].$file['name']).rand( 0, 100 );
	
			$this->smarty->assign( "count", $id );
			$this->smarty->assign( "item", $item );
	
			$sHtml .= $this->smarty->fetch( $this->config->get( 'TPL_DIR' )."forms/files_append.tpl" );
			$sScript .= '$("#gallery_'.$aFormValues['fieldname'].'_'.$id.'_appear").slideDown("slow");';
		}
		$this->objResponse->contextAppend( "container.innerHTML", $sHtml );
		$this->objResponse->contextAssign('outer_container.style.display','block');
		$this->objResponse->script( $sScript );

		$this->objResponse->call( 'Sortable.create', 'GallerySortable_'.$obj['obj_vers_id'].'_'.$aFormValues['fieldname'], array
		(
			"tag" => "div",
			"overlap" => 'horizontal',
			"constraint" => false
		));
		

		return $this->objResponse;
	}
	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerFileDetails( $aFormValues )
	{

		

		$root_dir = $this->getRootDir( $aFormValues ) ;

		$filedetails = $this->tools->getFileDetails( $root_dir,$aFormValues['dir'], $aFormValues['filename'] );
		$index = 'media' == $aFormValues['root'] ? true : false;
		
		$filedetails = $this->prepareFile($filedetails,$aFormValues['dir'],$aFormValues['root'],$root_dir,$index,true);
		$this->objResponse->script("this.detailView(".json_encode($filedetails).")");
		
		return $this->objResponse;
	}
 
	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerFileSave( $aFormValues )
	{

		

		$dest = $this->config->get( 'MEDIA_DIR' ).$aFormValues['dir'].$_FILES['upfile']['name'];
		$src = $_FILES['upfile']['tmp_name'];

		$res = move_uploaded_file( $src, $dest );

		if ( !$res )
			$this->objResponse->alert( "upload failed" );

		return $this->objResponse;
	}
	// -------------------------------------------------------------------------------------------------------------------

	function FileManagerFileSaveDetails( $aFormValues )
	{

		$this->objResponse->call('CMS.debugMessage','<pre>'.print_r($aFormValues,true).'</pre>');
		$query = "UPDATE file_index SET file_descr='".$this->ccdSQL->real_escape_string($aFormValues['values']['descr'])."', file_keywords='".$this->ccdSQL->real_escape_string($aFormValues['values']['keywords'])."' WHERE file_crc='".addslashes($aFormValues['id'])."' LIMIT 1";
		$this->objResponse->call('CMS.debugMessage','<pre>'.print_r($query,true).'</pre>');
		$res = $this->ccdSQL->query($query);


		return $this->objResponse;
	}


	function FileManagerSearch($aFormValues) {
		

		$root_dir = $this->getRootDir( $aFormValues ) ;

		$query = "SELECT * FROM file_index WHERE file_name like '".addslashes($aFormValues['sq'])."%'";
		$res = $this->ccdSQL->query($query);
		$files[] = array();

		while ($row = $this->ccdSQL->fetch_assoc($res)) {
				$file = array
				(
					"id" => $row['file_crc'],
					"end" => $this->tools->get_file_extension( $row['file_name'] ),
					"name" => $row['file_name'],
					"type" => $this->tools->get_file_type( $row['file_name'] ),
					"icon" => $this->tools->get_file_icon( $row['file_name'] ),
					"size" => $this->tools->getFileSize( $root_dir.$row['file_dir'].$row['file_name'] ),
					"path" => $row['file_dir']
				);


			$files[] = $file; 
		}

		$this->objResponse->script("
			$('#filemanager').filemanager('path','".$aFormValues['dir']."');
			$('#filemanager').filemanager('update',".json_encode($files).");
		");
		
		return $this->objResponse;
		
	}

	function addTemplates($params) 
	{
		$params[0][] = $this->smarty->fetch($this->tpl_dir.'templates.tpl');
	}



/* ---------------------------------------------------------------------------------------------------------------------------------- */

}


$ccdsModuleManager = ccdsModuleManager::getInstance();
$ccdsModuleManager->register('INIT_APP','ccdsFileManager','addTemplates');
?>